package com.magic.goods.service.impl;

import com.magic.goods.client.BrandClient;
import com.magic.goods.client.CategoryClient;
import com.magic.goods.client.GoodsClient;
import com.magic.goods.client.SpecificationClient;
import com.magic.goods.service.GoodsService;
import com.magic.item.pojo.Brand;
import com.magic.item.pojo.Category;
import com.magic.item.pojo.Sku;
import com.magic.item.pojo.SpecGroup;
import com.magic.item.pojo.SpecParam;
import com.magic.item.pojo.Spu;
import com.magic.item.pojo.SpuDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lan.jianyuan
 * @create 2021-01-27-13:11
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private SpecificationClient specificationClient;
    
    @Override
    public Map<String, Object> loadModel(Long spuId) {
        // 查询spu
        Spu spu = this.goodsClient.querySpuById(spuId);
        // 查询spu详情
        SpuDetail spuDetail = this.goodsClient.querySpuDetailBySpuId(spuId);
        // 查询sku
        List<Sku> skus = this.goodsClient.querySkuBySpuId(spuId);
        // 查询品牌
        Brand brand = this.brandClient.queryBrandById(spu.getBrandId());
        // 查询分类
        List<Category> categories = getCategories(spu);
        // 查询组内参数
        List<SpecGroup> specGroups = this.specificationClient.querySpecsByCid(spu.getCid3());
        // 查询所有特有规格参数
        List<SpecParam> specParams = this.specificationClient.queryParams(null, spu.getCid3(), false, null);
        // 处理规格参数
        Map<Long, String> paramMap = new HashMap<>();
        specParams.forEach(param -> {
            paramMap.put(param.getId(), param.getName());
        });
        Map<String, Object> map = new HashMap<>();
        map.put("spu", spu);
        map.put("spuDetail", spuDetail);
        map.put("skus", skus);
        map.put("brand", brand);
        map.put("categories", categories);
        map.put("groups", specGroups);
        map.put("params", paramMap);
        return map;
    }
    
    private List<Category> getCategories(Spu spu) {
        List<String> names = this.categoryClient.queryNamesByIds(
                Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        Category c1 = new Category();
        c1.setName(names.get(0));
        c1.setId(spu.getCid1());
        Category c2 = new Category();
        c2.setName(names.get(1));
        c2.setId(spu.getCid2());
        Category c3 = new Category();
        c3.setName(names.get(2));
        c3.setId(spu.getCid3());
        return Arrays.asList(c1, c2, c3);
    }
}
